package com.yupi.yuapiinterface.controller;

import com.yupi.yuapiclientsdk.model.User;
import com.yupi.yuapiclientsdk.utils.SignUtils;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;




@RestController
@RequestMapping("/name")
public class NameController {
    @GetMapping("/get")
    public String getNameByGet(String name) {
        return "GET 你的名字是" + name;
    }

    @PostMapping("/post")
    public String getNameByPost(@RequestParam String name) {
        return "POST 你的名字是:" + name;
    }

    @PostMapping("/user")
    public String getUserNameByPost(@RequestBody User user, HttpServletRequest httpServletRequest) {
        //String secretKey = httpServletRequest.getHeader("secretKey");  //秘钥不可在服务间传输

        //1.从请求头中拿到5个参数值做校验，比如accessKey,nonce,bodyMD5,timestamp
        String accessKey = httpServletRequest.getHeader("accessKey");
        String  nonce = httpServletRequest.getHeader("nonce");
        String timestamp = httpServletRequest.getHeader("timestamp");
        String sign = httpServletRequest.getHeader("sign");
        String body = httpServletRequest.getHeader("body");

        //1.权限校验，比如accessKey是否存在，是否过期，是否被禁用.  实际上是从数据库中插叙是否已分配给用户
        if (accessKey == null || !"yuapi".equals(accessKey)) {
            throw new RuntimeException("无权限");
        }

        //2.随机数校验
        if (nonce == null || Long.parseLong(nonce) > 10000) {
            throw new RuntimeException("无权限");
        }

        //3.时间和当前时间不超过5分钟
        if (new Date().getTime()/1000 - Long.parseLong(timestamp) > 60 * 5) {
            throw new RuntimeException("无权限");
        }

        //4.签名校验, 实际上是从数据库中查询出secretKey，然后进行签名校验
        String serveSign = SignUtils.genSign(body, "abcdefg");
        if (!sign.equals(serveSign)) {
            throw new RuntimeException("无权限");
        }
        //todo 调用次数+1

        String result = "POST 用户名字是:" + user.getUsername();

        return result;
    }
}
